package com.bupt.kgplatform.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.bupt.kgplatform.Util.R;
import com.bupt.kgplatform.Util.ResultCode;
import com.bupt.kgplatform.entity.User;
import com.bupt.kgplatform.entity.pojo.LoginInfo;
import com.bupt.kgplatform.mapper.UserMapper;
import io.netty.util.internal.ObjectUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.bupt.kgplatform.Util.*;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * LoginController
 *
 * @author zrz
 * @date 2024/3/25
 * @time 10:43
 * @Description 登陆类
 */
@RestController
@RequestMapping("/user1")
public class LoginController {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RedisCache redisCache;

    @PostMapping("/login")
    public R login (@RequestBody LoginInfo loginInfo){
        if(ObjectUtils.isEmpty(loginInfo.getUserName()) || ObjectUtils.isEmpty(loginInfo.getPwd())){
            return R.failure(ResultCode.FAILURE, "账号或者密码为空");
        }
        QueryWrapper<User> queryWrapper = new QueryWrapper<User>();
        queryWrapper.eq("user_name", loginInfo.getUserName());
        User user = userMapper.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(user)){
            return R.failure("用户不存在");
        }
        String redisKey = "user:" + user.getId();
        String token = redisCache.getCacheObject(redisKey);
        if(Objects.isNull(token)){
            // token不存在
            token = JwtUtil.createJWT(String.valueOf(user.getId()));
            //authenticate存入redis
            redisCache.setCacheObject("user:"+user.getId(), token,1, TimeUnit.DAYS);
        }


        return R.ok(token);
    }

}
